package com.mumu.android.tcp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

import com.mumu.android.tcp.data.Configuration;
import com.mumu.android.tcp.data.HostInfo;
import com.mumu.android.tcp.data.Param;

public class MainActivity extends BaseActivity {
    private EditText etRemoteIp, etRemotePort;
    private Configuration configuration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("TCP通信");

        initView();
        initObject();

        TextView btnToComm = findViewById(R.id.btn_saveAndStart);
        btnToComm.setOnClickListener(view -> toComm());
    }

    private void initView(){
        etRemoteIp = findViewById(R.id.tv_hostName);
        etRemotePort = findViewById(R.id.tv_port);
    }

    private void initObject(){
        configuration = new Configuration(context);
        HostInfo hostInfo = configuration.getHost();

        if(hostInfo.getPort()!=-1){
            etRemoteIp.setText(hostInfo.getHostName());
            etRemotePort.setText(String.valueOf(hostInfo.getPort()));
        }
    }


    private void toComm(){
        String ip = etRemoteIp.getText().toString();
        String port = etRemotePort.getText().toString();

        if (ip.isEmpty()) {
            showToast("IP不能为空");  return;
        }

        if (port.isEmpty()) {
            showToast("端口不能为空");  return;
        }

        int intPort = Integer.parseInt(port);
        if (intPort<0 || intPort>65536){
            showToast("输入的端口无效，请输入1~65535");  return;
        }

        // 保存数据
        Param.REMOTE_IP = ip;
        Param.REMOTE_PORT = intPort;
        configuration.saveHost(new HostInfo(ip, intPort));

        startActivity(new Intent(context, CommActivity.class));
    }
}